package com.wanjia.bpsapi.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wanjia.bpsapi.constant.CalType;
import com.wanjia.bpsapi.mapper.ParamMapper;
import com.wanjia.bpsapi.mapper.PutClientMapper;
import com.wanjia.bpsapi.pojo.dto.PutAwayDTO;
import com.wanjia.bpsapi.pojo.entity.Param;
import com.wanjia.bpsapi.pojo.entity.PutClient;
import com.wanjia.bpsapi.service.IPutClientService;
import com.wanjia.bpsapi.util.PageUtil;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

import static com.wanjia.bpsapi.constant.Constant.BIG_DECIMAL_SCALE;

/**
 * <p>
 * 上架信息表 服务实现类
 * </p>
 *
 * @author wyn
 * @since 2023-02-13
 */
@Service
public class PutClientServiceImpl extends ServiceImpl<PutClientMapper, PutClient> implements IPutClientService {

    @Setter(onMethod_ = @Autowired)
    private PutClientMapper mapper;

    @Setter(onMethod_ = @Autowired)
    private ParamMapper paramMapper;

    @Override
    public Page<PutAwayDTO> pagePutAway(Integer pageNo, Integer pageSize, Long vegeId, Long clientId, Date startPutDate, Date endPutDate) {
        // 查询分页数据与总数
        List<PutAwayDTO> records = mapper.pagePutAwayDTO(pageNo, pageSize, vegeId, clientId, startPutDate, endPutDate);
        Long total = mapper.countPutAwayDTO(vegeId, clientId, startPutDate, endPutDate);

        // 处理成本项列表
        Set<String> yuanPerOneParam = new HashSet<>();
        if (CollUtil.isNotEmpty(records)) {
            // 解析成本项id
            Set<Long> paramIds = new HashSet<>();
            Map<PutAwayDTO, List<Long>> paramIdMap = new HashMap<>();
            records.forEach(dto -> {
                List<Long> paramIdList = Optional.of(dto)
                        .map(PutAwayDTO::getCost)
                        .map(cost -> JSONUtil.toList(cost, Long.class))
                        .orElseGet(ArrayList::new);
                paramIdMap.put(dto, paramIdList);
                paramIds.addAll(paramIdList);
            });

            // 统一查询与创建映射表
            Map<Long, String> paramNameMap = new HashMap<>();
            if (CollUtil.isNotEmpty(paramIds)) {
                QueryWrapper<Param> wrapper = new QueryWrapper<>();
                wrapper.in("param_id", paramIds);
                List<Param> params = paramMapper.selectList(wrapper);
                Optional.ofNullable(params)
                        .orElseGet(ArrayList::new)
                        .forEach(p -> {
                            paramNameMap.put(p.getParamId(), p.getConsumable());
                            if (Objects.equals(p.getCaltype(), CalType.YUAN_PRE_ONE.code())) {
                                yuanPerOneParam.add(p.getConsumable());
                            }
                        });
            }

            // 成本项名称集合生成
            paramIdMap.forEach((dto, list) ->
                    dto.setCostList(list.stream()
                            .map(paramNameMap::get)
                            .filter(Objects::nonNull)
                            .collect(Collectors.toList())));
        }

        // 处理公斤单价
        records.forEach(p -> {
            BigDecimal putOffer = p.getPutOffer();
            if (putOffer != null) {
                boolean containYuanPerOne = p.getCostList().stream()
                        .anyMatch(yuanPerOneParam::contains);
                p.setPutOfferByKg(containYuanPerOne?putOffer:
                        putOffer.divide(BigDecimal.valueOf(1000), BIG_DECIMAL_SCALE, RoundingMode.HALF_UP));
            }
        });

        // 构建分页数据并返回
        return PageUtil.page(pageNo, pageSize, total, records);
    }
}
